import axios, {AxiosError, AxiosInstance, AxiosResponse, CreateAxiosDefaults} from "axios";
import {serverPort, serverIp} from "@/api/base_request/Server";
import {BaseRequest, BaseResult, ResultFile} from "@/api/base_request/index";

class Request implements BaseRequest {
    config: CreateAxiosDefaults = {
        timeout: 3 * 1000,
        baseURL: `http://${serverIp}:${serverPort}/`,
        withCredentials: true
    };

    instance: AxiosInstance;

    constructor() {
        this.instance = axios.create(this.config);
    }

    get<D>(url: string, params?: object) {
        return this.instance<any, AxiosResponse<D>, any>({url, method: "GET", params})
    }

    post<D>(url: string, data: Object) {
        return this.instance<any, AxiosResponse<D>, any>({url, method: "POST", data})
    }


    put<D>(url: string, params?: string) {
        return this.instance<any, AxiosResponse<D>, any>({url, method: "PUT", params})
    }

    delete<D>(url: string, params?: string){
        return this.instance<any, AxiosResponse<D>, any>({url, method: "DELETE", params})
    }

    download(url: string, params?: string) {
        return this.instance<any,AxiosResponse<ResultFile>,any>({url, method: "POST", params, responseType: "blob"})
    }

    interceptorResponse() {
        this.instance.interceptors.response.use(
            (response: AxiosResponse<BaseResult>) => {
                const {data} = response
                console.log(data.code);
                return response;
            },
            (err: AxiosError) => {
                return Promise.reject(err);
                ;
            }
        )
    }
}
export const request: BaseRequest = new Request()


